#include "freqtonotewidget.h"
#include "ui_freqtonotewidget.h"

freqToNoteWidget::freqToNoteWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::freqToNoteWidget)
{
    ui->setupUi(this);

    buildWidgets();
    setupConnections();

    updateNote();
}

freqToNoteWidget::~freqToNoteWidget()
{
    delete ui;
}

void freqToNoteWidget::buildWidgets()
{
    ui->temp_combo->clear();
    ui->temp_combo->addItems(TemperamentList());

    ui->concert_pitch_note_combo->clear();
    ui->concert_pitch_note_combo->addItems(PitchNoteList());
}

void freqToNoteWidget::setupConnections(void)
{
    this->connect(ui->freq_spin, SIGNAL(valueChanged(double)), this, SLOT(onDataChanged()));

    // Tuning system changed
    this->connect(ui->temp_combo, SIGNAL(currentIndexChanged(int)), this, SLOT(onDataChanged()));
    this->connect(ui->concert_pitch_freq_spin, SIGNAL(valueChanged(double)), this, SLOT(onDataChanged()));
    this->connect(ui->concert_pitch_note_combo, SIGNAL(currentIndexChanged(int)), this, SLOT(onDataChanged()));
}

void freqToNoteWidget::updateNote()
{
    // TODO: handle low/high frequencies
    // Frequency that is setted up
    qreal is_freq = ui->freq_spin->value();

    // Get info tuning system
    Temperament temp = toTemperament(ui->temp_combo->currentIndex());
    qreal baseFreq = ui->concert_pitch_freq_spin->value();
    Note baseNote = Note(ui->concert_pitch_note_combo->currentText());

    // DEbug: got base note correctly?
    //qDebug() << baseNote.toQString();

    // From freq get the note, tuned on pbase Freq and base Note
    Note note = Note(is_freq, baseFreq, baseNote, temp);
    //qDebug() << "Note:" << note.toQString();
    ui->note_line->setText(note.toQString());

    // Freq that should be (include temperament, ect...)
    qreal exact_freq = note.getFreq(baseFreq, baseNote, temp);
    ui->real_freq_spin->setValue(exact_freq);
    // Update difference spinbox
    ui->freq_diff_spin->setValue(exact_freq - is_freq);

    // Compute cents difference
    int cents = centsDiff(is_freq, exact_freq);
    ui->cents_diff_spin->setValue(cents);

    // Color spinbox (TODO: used in other places: unite!)
    int val = qAbs(cents);
    QPalette* palette = new QPalette();
    if ( val <= 50 ) {
        palette->setColor(QPalette::Background ,Qt::green);
    } else if ( val > 50 && val <= 100 ) {
        palette->setColor(QPalette::Background ,Qt::yellow);
    } else if ( val > 100 ) {
        palette->setColor(QPalette::Background ,Qt::red);
    }
    ui->cents_diff_spin->setPalette(*palette);

    // Set pixmap
    ui->preview_label->setPixmap(note.getQPixmap());
}

void freqToNoteWidget::onDataChanged()
{
    updateNote();
}
